package com.lagou.service;

import com.lagou.pojo.BaseResponse;
import com.lagou.pojo.DataResponse;
import com.lagou.pojo.User;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author
 */
@Service
public class QueryService {

    public BaseResponse query(){
        ComboPooledDataSource dataSource = DataSourceBuilder.getDataSource();
        if(dataSource == null){
            return BaseResponse.FAIL("请先调用/config，在zookeeper中设置数据源参数！");
        }
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = null;
        try {
            connection = dataSource.getConnection();
            String sql = "select * from user where id = 1";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            user = new User();
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                user.setId(id);
                user.setName(username);
            }
            System.out.println(user);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        if(user == null){
            return BaseResponse.FAIL();
        } else {
            return DataResponse.SUCCESS(user);
        }
    }

}
